package com.jollychic.www.roomdatebasedemo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jollychic.www.roomdatebasedemo.DaoManager;
import com.jollychic.www.roomdatebasedemo.R;
import com.jollychic.www.roomdatebasedemo.adapter.AdapterList;
import com.jollychic.www.roomdatebasedemo.model.StoreEntity;
import com.jollychic.www.roomdatebasedemo.model.result.InnerResultGoodsModel;
import com.jollychic.www.roomdatebasedemo.model.result.InnerResultModel;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * desc: 查询 <br/>
 * author: 李超杰 <br/>
 * time: 2018/4/22 17:42 <br/>
 * since: V 6.1X <br/>
 */

public class FragmentRetrieve extends Fragment {

    private static final String TAG = "FragmentRetrieve";

    //查询 id
    private AppCompatEditText queryId;
    private AppCompatEditText queryName;
    private AppCompatButton queryButton;
    private AppCompatButton queryMulButton;
    private AppCompatEditText limit;

    private final List<StoreEntity> LIST = new ArrayList<>();
    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container
            , @Nullable Bundle savedInstanceState) {
        final View view = LayoutInflater.from(getContext())
                .inflate(R.layout.fragment_retrieve, container, false);
        queryButton = view.findViewById(R.id.bt_query);
        queryMulButton = view.findViewById(R.id.bt_query_mul);
        queryId = view.findViewById(R.id.et_query_id);
        queryName = view.findViewById(R.id.et_query_name);
        recyclerView = view.findViewById(R.id.rv_list);
        limit = view.findViewById(R.id.et_query_limit);
        initListener();

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        final AdapterList adapter = AdapterList.createAdapter(getContext(), LIST);
        recyclerView.setAdapter(adapter);
        return view;
    }

    private void initListener() {
        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                query();
            }
        });

        queryMulButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryMul();
            }
        });
    }


    private void query() {
        if (TextUtils.isEmpty(getQueryName()) && TextUtils.isEmpty(getQueryId())) {
            queryList();
        } else if (!TextUtils.isEmpty(getQueryId())) {
            queryByStoreId();
        } else {
            if (getLimit() > 0) {
                queryByLimit();
            } else {
                queryByName();
            }
        }
    }

    private void queryList() {
        getStoreEntityListObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<List<StoreEntity>>() {
                    @Override
                    public void onNext(List<StoreEntity> storeEntities) {
                        update(storeEntities);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void queryByStoreId() {
        getStoreEntityObservable(getQueryId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<StoreEntity>() {
                    @Override
                    public void onNext(StoreEntity storeEntity) {
                        if (storeEntity != null) {
                            LIST.clear();
                            final ArrayList<StoreEntity> storeEntities = new ArrayList<>();
                            storeEntities.add(storeEntity);
                            update(storeEntities);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void queryByName() {
        getStoreEntityByName(getQueryName())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<List<StoreEntity>>() {
                    @Override
                    public void onNext(List<StoreEntity> storeEntities) {
                        update(storeEntities);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void queryByLimit() {
        getStoreEntityListObservable(getLimit(), getQueryName())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<List<StoreEntity>>() {
                    @Override
                    public void onNext(List<StoreEntity> storeEntities) {
                        update(storeEntities);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void update(List<StoreEntity> storeEntities) {
        if (storeEntities != null) {
            LIST.clear();
            LIST.addAll(storeEntities);
            recyclerView.getAdapter().notifyDataSetChanged();
        }
    }

    private String getQueryName() {
        return queryName.getText().toString().trim();
    }

    private String getQueryId() {
        return queryId.getText().toString().trim();
    }

    private int getLimit() {
        String trim = limit.getText().toString().trim();
        return TextUtils.isEmpty(trim) ? 0 : Integer.parseInt(trim);
    }

    private Observable<List<StoreEntity>> getStoreEntityListObservable() {
        return DaoManager.getInstance().getIStoreDao()
                .getRxStoresList()
                .toObservable();
    }

    private Observable<StoreEntity> getStoreEntityObservable(String id) {
        return DaoManager.getInstance().getIStoreDao()
                .getRxStoreByStoreId(id)
                .toObservable();
    }

    private Observable<List<StoreEntity>> getStoreEntityByName(String name) {
        return DaoManager.getInstance().getIStoreDao()
                .getRxStoreListByName(name)
                .toObservable();
    }

    private Observable<List<StoreEntity>> getStoreEntityListObservable(int max, String... name) {
        return DaoManager.getInstance().getIStoreDao()
                .getRxStoreListByName(max, name)
                .toObservable();
    }

    /**
     * 多表查询
     */
    private void queryMul() {
        Completable.fromRunnable(new Runnable() {
            @Override
            public void run() {
//                final List<InnerResultModel> innerResultModels = DaoManager.getInstance().getIDrinkDao().queryMul();
//                if(innerResultModels != null && !innerResultModels.isEmpty()){
//                    for (InnerResultModel innerResultModel : innerResultModels) {
//                        final String id = innerResultModel.getStoreId();
//                        final String storeName = innerResultModel.getStoreName();
//
//                        final double price = innerResultModel.getDrinkPrice();
//                        final String brand = innerResultModel.getDrinkBrand();
//
////                        Log.i(TAG, "storeId:"+id+"===name:"+storeName);
//                        Log.i(TAG, "storeId:"+id+"===name:"+storeName+"===price:"+String.valueOf(price)+"===brand:"+brand);
//
//                    }
//                }

                final List<InnerResultGoodsModel> innerResultGoodsModels = DaoManager.getInstance().getIGoodsDao().queryMul();
                if (innerResultGoodsModels != null && innerResultGoodsModels.size() > 0) {
                    for (InnerResultGoodsModel innerResultGoodsModel : innerResultGoodsModels) {
                        final String storeId = innerResultGoodsModel.getStoreId();
                        final String name = innerResultGoodsModel.getStoreName();
                        final String goodId = innerResultGoodsModel.getGoodId();
                        Log.i(TAG, "storeId:" + storeId + "===name:" + name + "===goodId:" + goodId);
                    }
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();

    }

}
